using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using FederatedScaleOutDatabases.Interfaces;

namespace FederatedScaleOutDatabases.Repositories
{
    public class Repository<T> : IRepository<T> where T : class
    {
        private readonly DbContext _dbContext;
        private readonly DbSet<T> _entities;
        private bool _isDisposed;
        public Repository(DbContext dbContext)
        {
            _dbContext = dbContext;
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DbContext>());
            _dbContext.Database.Initialize(false);
            _entities = _dbContext.Set<T>();
        }

        public void Add(T entity)
        {
            _entities.Add(entity);
        }

        public IEnumerable<T> Get(System.Linq.Expressions.Expression<Func<T, bool>> condition)
        {
            return _entities.Where(condition);
        }

        public void Update(T entity)
        {
            _entities.Attach(entity);
            _dbContext.Entry<T>(entity).State = System.Data.EntityState.Modified;
        }

        public void Delete(T entity)
        {
            _entities.Remove(entity);
        }


        public void SaveChanges()
        {
            _dbContext.SaveChanges();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected void Dispose(bool disposing)
        {
            if (!_isDisposed)
            {
                if (disposing)
                    _dbContext.Dispose();
            }
            _isDisposed = true;
        }
    }
}
